<template>
  <div>
    <h2>订单管理</h2>

    <!-- 订单表格 -->
    <table>
      <thead>
      <tr>
        <th>订单ID</th>
        <th>用户名</th>
        <th>订单状态</th>
        <th>订单日期</th>
        <th>总金额</th>
        <th>订单状态</th>
        <th>查看详情</th>

      </tr>
      </thead>
      <tbody>
      <tr v-for="order in orders" :key="order.orderId">
        <td>{{ order.orderId }}</td>
        <td>{{ order.username }}</td> <!-- 显示用户名 -->
        <td>{{ formatOrderStatus(order.orderStatus) }}</td>
        <td>{{ order.orderDate }}</td>
        <td>{{ order.totalPrice }}</td>
        <td>{{ formatShipmentStatus(order.shipmentStatus) }}</td>
        <td>
          <button @click="fetchOrderDetails(order.orderId)">查看详情</button>

        </td>
      </tr>
      </tbody>
    </table>

    <!-- 分页组件 -->
    <Pagination
        :current-page="currentPageNumber"
        :total="totalOrders"
        :page-size="pageSize"
        @update:currentPage="handlePageChange"
    />

    <!-- 订单详情区域 -->
    <div v-if="selectedOrderDetails.length > 0">
      <table>
        <thead>
        <tr>
          <th>商品ID</th>
          <th>数量</th>
          <th>价格</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="detail in selectedOrderDetails" :key="detail.detailId">
          <td>{{ detail.productId }}</td>
          <td>{{ detail.quantity }}</td>
          <td>{{ detail.price }}</td>
        </tr>
        </tbody>
      </table>

      <!-- 分页组件 for order details -->
      <Pagination
          :current-page="detailPageNumber"
          :total="totalOrderDetails"
          :page-size="pageSize"
          @update:currentPage="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import Pagination from '@/components/Pagination.vue';
import axios from 'axios';
import user from "./User.vue";

export default {
  computed: {
    user() {
      return user
    }
  },
  components: {
    Pagination,
  },
  props: {
    currentPageNumber: {
      type: Number,
      required: true,
    },
    pageSize: {
      type: Number,
      required: true,
    },
  },
  setup(props, { emit }) {
    const orders = ref([]);
    const totalOrders = ref(0);
    const selectedOrderDetails = ref([]);
    const totalOrderDetails = ref(0);
    const detailPageNumber = ref(1);
    const formatOrderStatus = (status) => {
      switch (status) {
        case 1:
          return '待支付';
        case 2:
          return '已支付';
        default:
          return '未知状态';
      }
    };
    const formatShipmentStatus = (status) => {
      switch (status) {
        case 0:
          return '未催促';
        case 1:
          return '已催货，加急';
        default:
          return '未知状态';
      }
    };


    // 获取订单列表数据
    const fetchOrders = async (pageNum, pageSize) => {
      try {
        const response = await axios.post('admins/selectAllOrders', {
          pageNum,
          pageSize,
        });
        const ordersData = response.data.records;

        // 获取所有 userId
        const userIds = ordersData.map(order => order.userId);


        // 查询用户信息
        const usersResponse = await axios.post('admins/getUsernamesByIds',  userIds );

        const users = usersResponse.data;



        // 替换 userId 为 username
        orders.value = ordersData.map(order => {

console.log(users)
          const user = users.find(user => user.id = order.userId);



          return {
            ...order,
            username: user ? user.username : '未知用户',
          };
        });

        totalOrders.value = response.data.total;

      } catch (error) {
        console.error('Failed to fetch orders:', error);
      }
    };

    // 获取订单详情数据
    const fetchOrderDetails = async (orderId) => {

      try {
        const response = await axios.post('admins/selectOrderDetails', {
          orderId,
          pageNum: detailPageNumber.value,
          pageSize: props.pageSize,
        });
        selectedOrderDetails.value = response.data.records;
        totalOrderDetails.value = response.data.total;
      } catch (error) {
        console.error('Failed to fetch order details:', error);
      }
    };

    // 处理分页变更
    const handlePageChange = (newPage) => {
      emit('update:currentPageNumber', newPage);
      fetchOrders(newPage, props.pageSize);
    };

    // 处理订单详情分页变更
    const handleDetailPageChange = (newPage) => {
      detailPageNumber.value = newPage;
      fetchOrderDetails(selectedOrderDetails.value[0]?.orderId); // Assuming the orderId is the same for all details
    };

    // 初始化时加载订单数据
    fetchOrders(props.currentPageNumber, props.pageSize);

    return {
      orders,
      totalOrders,
      selectedOrderDetails,
      totalOrderDetails,
      handlePageChange,
      handleDetailPageChange,
      fetchOrderDetails,
      formatOrderStatus,
      formatShipmentStatus,


    };
  },
};
</script>

<style scoped>
/* 样式 */
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

table th,
table td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: left;
}

button {
  padding: 5px 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style>
